/**
 * 
 */
package com.android.gtdroid;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author xiang
 * 
 */
public class ViewAct extends Activity {
	private final String tag = "ViewAct";
	private final int DLG_ID_ADD = 0;
	private final int DLG_ID_EDIT = 1;
	private final int DLG_ID_DEL = 2;

	private ListView lv;
	private ArrayAdapter<String> aa;
	private Button btn_add, btn_edit, btn_del, btn_return;
	private int select;
	private Dialog dlg;
	private Bundle bd;
	private int viewCode;

	private GTDApp ga;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		Log.i(tag, "now onCreate method is called!");

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.view_cmn);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tb_cmn);
		ga = (GTDApp) getApplication();

		lv = (ListView) findViewById(R.id.lv);
		btn_add = (Button) findViewById(R.id.btn_add);
		btn_edit = (Button) findViewById(R.id.btn_edit);
		btn_del = (Button) findViewById(R.id.btn_del);
		btn_return = (Button) findViewById(R.id.btn_return);

		bd = getIntent().getExtras();
		viewCode = bd.getInt("view_code");

		displayView();

		handleEvent();

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		Log.i(tag, "now onDestroy method is called!");

		super.onDestroy();
	}

	private void handleEvent() {
		Button btn_new = (Button) findViewById(R.id.btn_new);
		btn_new.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(ListAct.DLG_ID_ADD);
			}
		});

		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub

				String str = "";
				if (arg2 > 0)		// except the default no context, no project, no position
					str = (String) lv.getItemAtPosition(arg2);
				((CheckedTextView) lv.getChildAt(arg2)).setChecked(true);

				/*Toast toast = Toast.makeText(getApplicationContext(),
						"you checked me: " + str, Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();*/

				Intent itt = new Intent();
				Bundle bdl = new Bundle();
				bdl.putString("selected", str);		// selected item
				bdl.putInt("pos", arg2);			// the position in the list
				bdl.putInt("code", viewCode);		// one of context, project and position
				itt.putExtras(bdl);

				setResult(RESULT_OK, itt);
				finish();
			}
		});

		lv.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				CheckedTextView v = (CheckedTextView) arg1;

				if (arg2 != 0) {
					btn_edit.setEnabled(true);
					btn_del.setEnabled(true);
				} else {
					btn_edit.setEnabled(false);
					btn_del.setEnabled(false);
				}

				// int chk = lv.getCheckedItemPosition();
				// lv.setItemChecked(chk, false);
				lv.setItemChecked(arg2, true);
				// v.setChecked(true);
				select = arg2;

				return true;
			}
		});

		btn_add.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(DLG_ID_ADD);
			}
		});
		btn_edit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(DLG_ID_EDIT);
			}
		});

		btn_del.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ArrayList<String> al = getData(viewCode);
				al.remove(select);
				setData(viewCode, al);

				Editor edit = null;
				switch (viewCode) {
				case C.TASK.CONTEXT: // context
					edit = ga.getSpContexts().edit();
					edit.remove("Context[" + select + "]");

					break;
				case C.TASK.PROJECT: // project
					edit = ga.getSpProjects().edit();
					edit.remove("Project[" + select + "]");

					break;
				case C.TASK.POSITION: // position
					edit = ga.getSpPositions().edit();
					edit.remove("Position[" + select + "]");

					break;
					
				default:
					break;
				}

				if (edit != null)
					edit.commit();
				else
					Log.e(tag, "del: edit is null with view code" + viewCode);

				edit.putInt("count", al.size());
				edit.commit();

				aa.notifyDataSetChanged();
			}
		});

		btn_return.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		Window window;

		switch (id) {
		case ListAct.DLG_ID_ADD:
			dlg = new Dialog(this);
			window = dlg.getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
					WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
			dlg.setTitle(getString(R.string.add));
			dlg.setContentView(R.layout.dialog_view);

			break;
		case ListAct.DLG_ID_EDIT:
			dlg = new Dialog(this);
			window = dlg.getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
					WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
			dlg.setTitle(getString(R.string.edit));
			dlg.setContentView(R.layout.dialog_view);

			break;
		case DLG_ID_DEL:
			break;
		default:
			dlg = null;

			break;
		}

		return dlg;
	}

	private ArrayList<String> getData(int viewCode) {
		ArrayList<String> al = null;

		switch (viewCode) {
		case C.TASK.CONTEXT:
			al = ga.getContexts();

			break;
		case C.TASK.PROJECT:
			al = ga.getProjects();

			break;
		case C.TASK.POSITION:
			al = ga.getPositions();

			break;
		default:
			break;
		}

		return al;
	}

	private void setData(int viewCode, ArrayList<String> al) {
		switch (viewCode) {
		case C.TASK.CONTEXT:
			ga.setContexts(al);
			break;
		case C.TASK.PROJECT:
			ga.setProjects(al);
			break;
		case C.TASK.POSITION:
			ga.setPositions(al);
			break;
		default:
			break;
		}
	}

	@Override
	public void onPrepareDialog(int id, Dialog dialog) {
		Button btn_ok = (Button) dlg.findViewById(R.id.btn_ok);
		Button btn_cal = (Button) dlg.findViewById(R.id.btn_cal);
		EditText text = (EditText) dlg.findViewById(R.id.dlg_edit_text);

		btn_cal.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				dlg.dismiss();
			}
		});

		switch (id) {
		case (DLG_ID_ADD):
			text.setText("");
			text.setFocusable(true);

			btn_ok.setOnClickListener(new Button.OnClickListener() {
				public void onClick(View v) {
					EditText et = (EditText) dlg
							.findViewById(R.id.dlg_edit_text);
					String str = et.getText().toString();
					ArrayList<String> al = new ArrayList<String>();

					if (str.length() > 0) {
						Editor edit = null;

						switch (viewCode) {
						case C.TASK.CONTEXT: // context
							al = ga.getContexts();
							al.add(str);
							ga.setContexts(al);

							edit = ga.getSpContexts().edit();
							edit.putString("Context[" + (al.size() - 1) + "]",
									str);

							break;
						case C.TASK.PROJECT: // project
							al = ga.getProjects();
							al.add(str);
							ga.setProjects(al);

							edit = ga.getSpProjects().edit();
							edit.putString("Project[" + (al.size() - 1) + "]",
									str);

							break;
						case C.TASK.POSITION: // position
							al = ga.getPositions();
							al.add(str);
							ga.setPositions(al);

							edit = ga.getSpPositions().edit();
							edit.putString("Position[" + (al.size() - 1) + "]",
									str);

							break;
							
						default:
							break;
						}

						edit.putInt("count", al.size());
						edit.commit();

						aa.notifyDataSetChanged();
					} else {
						Toast toast = Toast.makeText(ViewAct.this,
								getString(R.string.empty_warning), Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();

						return;
					}

					dlg.dismiss();
				}
			});
			break;
		case (DLG_ID_EDIT):
			ArrayList<String> al = getData(viewCode);
			text.setText(al.get(select).toString());
			text.selectAll();

			btn_ok.setOnClickListener(new Button.OnClickListener() {
				public void onClick(View v) {
					EditText et = (EditText) dlg
							.findViewById(R.id.dlg_edit_text);
					String str = et.getText().toString();

					if (str.length() > 0) {
						ArrayList<String> al = getData(viewCode);
						al.set(select, str);
						setData(viewCode, al);

						Editor edit = null;
						switch (viewCode) {
						case C.TASK.CONTEXT: // context
							edit = ga.getSpContexts().edit();
							edit.putString("Context[" + select + "]", str);

							break;
						case C.TASK.PROJECT: // project
							edit = ga.getSpProjects().edit();
							edit.putString("Project[" + select + "]", str);

							break;
						case C.TASK.POSITION: // position
							edit = ga.getSpPositions().edit();
							edit.putString("Position[" + select + "]", str);

							break;
							
						default:
							break;
						}

						if (edit != null)
							edit.commit();
						else
							Log.e(tag, "edit is null with view code" + viewCode);

						aa.notifyDataSetChanged();
					} else {
						Toast toast = Toast.makeText(ViewAct.this,
								getString(R.string.empty_warning),
								Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();

						return;
					}

					dlg.dismiss();
				}
			});

			break;
		case DLG_ID_DEL:
			break;
		default:
			break;
		}
	}

	private void displayView() {
		ArrayList<String> data = null;

		int viewCode = bd.getInt("view_code");
		String viewName = bd.getString("view_name");

		switch (viewCode) {
		case C.TASK.CONTEXT: // context
			data = ga.getContexts();
			break;
			
		case C.TASK.PROJECT: // project
			data = ga.getProjects();
			break;
			
		case C.TASK.POSITION: // position
			data = ga.getPositions();
			break;
			
		default:
			break;
		}

		aa = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_single_choice, data);
		lv.setAdapter(aa);

		// if (viewCode == 3) { // tags can be multi-selected
		// lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		// } else {
		lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		lv.setItemChecked(bd.getInt("pos"), true);
		// }

		((TextView) findViewById(R.id.tv_title)).setText(viewName);
		((TextView) findViewById(R.id.btn_new)).setVisibility(View.INVISIBLE);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}
}
